{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cell(size, residual, reuse=False):\n",
    "            c = tf.nn.rnn_cell.GRUCell(size,reuse=reuse)\n",
    "            if residual:\n",
    "                c = tf.nn.rnn_cell.ResidualWrapper(c)\n",
    "            return c\n",
    "        \n",
    "        def cells(size = size_layer, residual = 1, reuse=False):\n",
    "            cell_list = []\n",
    "            for i in range(num_layers):\n",
    "                cell_list.append(cell(size, i >= residual, reuse=reuse))\n",
    "            return cell_list\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell(cells(reuse=reuse)), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell(cells()), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "        \n",
    "        states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-91485144153b>:12: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-91485144153b>:42: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-91485144153b>:45: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[31388, 28150, 16180,  6919,  6919,  6866,  6573,  6573,  6573,\n",
       "          6874,  3797, 29300, 29300, 29300, 10576, 19326, 19326, 11659,\n",
       "         11659, 11659, 11659,  2286, 11659, 11659,  2286, 31079, 18128,\n",
       "          3603,  3603, 11604,  3016, 13601, 13601,  5148,  5148, 11604,\n",
       "          5148,  5148, 11604,  5148,  5148,  5148,  5148,  5148, 30807,\n",
       "         19009, 19009,  7310, 20684, 12319, 12319, 11553, 11553, 11553,\n",
       "         11553, 29893, 28315, 11604, 19277,  6431,  6431,  4472,  4472,\n",
       "         11945, 11945,  1248, 16250, 16250, 16250, 16250, 16250, 16250],\n",
       "        [26215, 20221, 31003, 31003, 31003, 31003, 25104, 25104, 10623,\n",
       "         28578, 12628,  9565,  1619,  9565,  9565,  9565, 28164, 30223,\n",
       "          4401, 30223, 28611, 28611, 27379, 27379, 27379, 27379, 23346,\n",
       "         23346,  1179, 23346, 16376, 19601, 18640, 31787, 31787,  8235,\n",
       "         31787,  8235, 31787, 11192,  7572,  7572,  7572,  7572,  7572,\n",
       "          7572,  7572,  7572,  7572,  7572,  7572,  6822, 18618, 24136,\n",
       "         24136, 24136, 24136,  1244, 24136,  1244,  3970,  9457, 16757,\n",
       "         16757, 23463, 23463, 23463, 24136, 24136, 24136, 16757, 16757],\n",
       "        [18723, 16359,  9211,  4150, 18669,  4080,  8011,  7420, 23970,\n",
       "         30662,  6350, 10663,  7983,  7983, 26171,  4135, 16555, 20001,\n",
       "         30491, 30491, 30491, 30491, 30491, 18101, 31447, 11307, 11307,\n",
       "          3970, 13068, 13068, 13068, 13068,  3008,  3008, 24522, 24522,\n",
       "         24522, 17974,   211,  7929,   211, 31338, 31338, 31338,   349,\n",
       "          2144, 23597, 23597, 19987, 18434, 18669, 27313, 23597, 19987,\n",
       "          9153,  9153,  9153, 23102, 27543, 17771, 29149, 25286,  9590,\n",
       "         12220, 30916, 30916, 22569, 22569, 25209, 22569,  5066,  1343],\n",
       "        [26541,  6226, 12097, 12097, 23367,  8503, 27767, 22069, 21095,\n",
       "         21095, 21084, 20737, 28095, 28095,   716,  8003,   716,  8003,\n",
       "          6720, 28751,  8003, 22354, 22354, 13665,  8003, 22354, 13665,\n",
       "          8003, 22354, 13665, 19341, 19341, 19341, 19341, 29149, 30645,\n",
       "         28223, 28223, 11023, 22114, 22114, 21128, 26608,  6998,  6998,\n",
       "          6998,  6998, 30027, 30027, 30027, 30027, 28010, 30582, 30582,\n",
       "         30582, 30582, 12050, 26099, 29223, 28546, 28546, 28546, 26099,\n",
       "          4003, 26099,  4003, 31376,  1059, 12519, 15929,  8503,  8503],\n",
       "        [15161, 13351, 22778, 17879, 13351, 31868, 31868, 31868, 31868,\n",
       "         31868,  7712,  4672,  4672,  4672,  4672,  4672,  4672,  7572,\n",
       "          7572,  7572,  7572,  7572,  7572, 10092, 10092, 19790, 19390,\n",
       "         17189, 18431, 23658, 14879, 23658,  3698, 14879,  3698, 14879,\n",
       "          3698, 24628,  9274, 22876, 23617, 23617, 23617, 22210, 27410,\n",
       "         27410, 12271, 27410, 12271, 27410, 12271,  5891, 27490,  5452,\n",
       "          5452,  5452,  6381,  5452,  6381,  5452, 30018, 30018, 23649,\n",
       "         23649, 23649,  2584,  2584,  2584,  2584,  2584,  2584, 10234],\n",
       "        [25184, 24488,   931,   931, 15266,  1630,  9623,  9623, 27718,\n",
       "         27718, 27718, 10151, 10151,  1315, 18776, 14204,  3028, 16338,\n",
       "         27421, 15412, 16617,   530,   530,   530, 18215, 18215, 20011,\n",
       "         10244,  3052,  3052,  3052,  3052, 27003,  3052, 27003,  3052,\n",
       "         27003,  3052, 27003, 27003, 31724, 29984,  3465, 29984, 29984,\n",
       "          3465, 10578, 10578, 17837, 17837, 17837, 17837, 17837,  6401,\n",
       "         30543, 30543, 30543, 30543,  1882, 27032, 27032, 13316, 27032,\n",
       "         13316, 30910, 27032, 30179, 30179, 28587,  2640,  6385,  6385],\n",
       "        [10368, 15895, 15895, 15895, 15895, 15255, 25083, 25083, 25083,\n",
       "          8501,  8501,  8501,  3315, 11179, 11179, 22950, 11179, 22950,\n",
       "         11179, 22950, 11179, 11179,  9686,  3988,  3988,  3988,  3988,\n",
       "          4979,  4979,  9736,  4979, 22377, 22377, 22377, 22377, 22377,\n",
       "         22377, 22377, 22377, 22377, 25180, 25180, 14586, 14586, 14586,\n",
       "         17399, 25180, 27590, 17399, 11807, 11807, 11807, 11807, 11807,\n",
       "         11807, 11807, 11807, 30169, 11807, 23702, 23702, 30169, 30169,\n",
       "         30169, 30169, 19384, 19384,  7597,  7597,  7597,  7597, 28696],\n",
       "        [11178,  2126,   852, 20236, 17525,  9149,  9149, 18438, 10058,\n",
       "         10058, 10058, 18438, 10058,  1089, 25468, 23640, 14729, 14729,\n",
       "         25468, 14826, 27081, 16864, 16864, 13690, 13690, 11723, 13690,\n",
       "         10700, 13690, 10700,  3394, 17525, 17525, 17525, 27297, 17456,\n",
       "         10528, 10528, 25083, 25083, 25083, 25083, 22553, 25083, 12291,\n",
       "         12291, 12291, 22694,  4017, 18744, 27530, 27530, 15042, 15042,\n",
       "         15042, 20996, 20996,  9749,  9749,  9492, 16067, 29667, 29667,\n",
       "         29667,  5022, 28662,  3234, 11835, 11835, 11835, 11835, 11835],\n",
       "        [ 2964, 11628, 25983, 25983,  7179, 31699, 28850, 28850, 30261,\n",
       "         23299, 23299,  7866,  7866, 19942,  7866, 28898, 10425, 10425,\n",
       "         11622, 24974, 17892,  6537,  6537,  6537,  6537, 30521,  6537,\n",
       "         30595, 14775, 14775, 14775, 14775, 14775, 14775, 14775, 14775,\n",
       "         30358, 20547, 25106, 25106, 25106, 25106,  4035,  1973,  1973,\n",
       "          4035, 19748, 19748, 19748, 19748, 27381,  4268, 30399, 27381,\n",
       "          2158, 23847,  2158, 23847, 23847, 11411, 23847, 24335, 24335,\n",
       "          9674,    10, 19077,  1888,  1888,  1888, 27861, 26380, 30595],\n",
       "        [15440, 15440, 15440,  1120, 30332, 17304, 17304, 17304, 17304,\n",
       "         15861, 15736, 30194, 29671, 29671,  1551, 22475, 29671, 29671,\n",
       "         25726, 25726, 11818,  5322, 11818, 25326, 31583,  5322, 25326,\n",
       "         31583,  9514,  9514,  9217,  9217, 25326,  9227,  9227,  9227,\n",
       "          9227,  5345,  9227,  5345,  9227,  9227,  9227,  9227,  7156,\n",
       "          7156,  7156, 26868, 26868, 26868, 23870, 23870, 26560, 26560,\n",
       "         26560, 26560, 26560,  2615, 13758, 13758, 11716, 11716,  9702,\n",
       "          9702,  6636,  6636,  6636, 16759,   159, 16402, 31991, 31991]],\n",
       "       dtype=int32), 10.376651, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.415, cost=3.48]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.87it/s, accuracy=0.462, cost=2.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 4.543955, training avg acc 0.302964\n",
      "epoch 1, testing avg loss 3.333300, testing avg acc 0.421786\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.525, cost=2.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.505, cost=2.56]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 2.930923, training avg acc 0.463940\n",
      "epoch 2, testing avg loss 2.888315, testing avg acc 0.474904\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.558, cost=2.14]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.538, cost=2.48]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.435395, training avg acc 0.523126\n",
      "epoch 3, testing avg loss 2.860576, testing avg acc 0.477277\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.621, cost=1.75]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.522, cost=2.33]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.151717, training avg acc 0.559847\n",
      "epoch 4, testing avg loss 2.792870, testing avg acc 0.488330\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:10<00:00,  2.33it/s, accuracy=0.666, cost=1.48]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.532, cost=2.43]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 1.952186, training avg acc 0.587040\n",
      "epoch 5, testing avg loss 2.836170, testing avg acc 0.493399\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.695, cost=1.3] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.548, cost=2.45]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.795686, training avg acc 0.609433\n",
      "epoch 6, testing avg loss 2.907520, testing avg acc 0.493597\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:13<00:00,  2.32it/s, accuracy=0.702, cost=1.21]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.511, cost=2.71]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.688196, training avg acc 0.624575\n",
      "epoch 7, testing avg loss 3.007074, testing avg acc 0.483500\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:13<00:00,  2.32it/s, accuracy=0.728, cost=1.07]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.559, cost=2.68]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.595570, training avg acc 0.638451\n",
      "epoch 8, testing avg loss 3.006897, testing avg acc 0.494628\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.731, cost=1.01]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.543, cost=2.59]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.515025, training avg acc 0.650782\n",
      "epoch 9, testing avg loss 3.075107, testing avg acc 0.492175\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:13<00:00,  2.32it/s, accuracy=0.751, cost=0.959]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.522, cost=2.68]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.442713, training avg acc 0.662562\n",
      "epoch 10, testing avg loss 3.153999, testing avg acc 0.486143\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.746, cost=0.932]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.532, cost=2.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.393297, training avg acc 0.669794\n",
      "epoch 11, testing avg loss 3.248554, testing avg acc 0.488943\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.748, cost=0.988]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.527, cost=2.94]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.354868, training avg acc 0.675427\n",
      "epoch 12, testing avg loss 3.408419, testing avg acc 0.478185\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.32it/s, accuracy=0.758, cost=0.937]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.543, cost=2.94]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.314482, training avg acc 0.682237\n",
      "epoch 13, testing avg loss 3.478434, testing avg acc 0.470707\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.78, cost=0.838]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.527, cost=2.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.280590, training avg acc 0.687464\n",
      "epoch 14, testing avg loss 3.440728, testing avg acc 0.477677\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.775, cost=0.838]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.548, cost=2.77]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 1.287011, training avg acc 0.685296\n",
      "epoch 15, testing avg loss 3.474909, testing avg acc 0.481107\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.786, cost=0.758]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.565, cost=2.8] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 1.246637, training avg acc 0.692879\n",
      "epoch 16, testing avg loss 3.519033, testing avg acc 0.486903\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.794, cost=0.754]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.543, cost=3.19]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 1.188650, training avg acc 0.704092\n",
      "epoch 17, testing avg loss 3.583795, testing avg acc 0.483301\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:14<00:00,  2.32it/s, accuracy=0.793, cost=0.759]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.527, cost=3]   \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 1.176895, training avg acc 0.705653\n",
      "epoch 18, testing avg loss 3.643275, testing avg acc 0.479509\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:15<00:00,  2.31it/s, accuracy=0.799, cost=0.728]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.96it/s, accuracy=0.532, cost=3.07]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 1.166428, training avg acc 0.707088\n",
      "epoch 19, testing avg loss 3.661750, testing avg acc 0.479595\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:58<00:00,  2.37it/s, accuracy=0.781, cost=0.793]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.90it/s, accuracy=0.527, cost=3.24]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.154090, training avg acc 0.709127\n",
      "epoch 20, testing avg loss 3.693631, testing avg acc 0.476915\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook\n",
    "\n",
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)\n",
    "    \n",
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])\n",
    "    \n",
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
